<template>
  <el-dialog v-model="drawer" title="草稿箱" width="700px" :append-to-body="true" @close="close">
    <el-table :data="list" size="small">
      <el-table-column label="客户名称" prop="memberUsername"></el-table-column>
      <el-table-column label="创建时间" prop="createTime"></el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button type="primary" size="small" link @click="editDraft(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" link @click="delDraft(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <create-order title="新增订单" v-model:dialogDrawer="dialogEdit"></create-order>
  </el-dialog>
</template>

<script>
import { computed, reactive, toRefs, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useOrderApi } from '/@/api/order/index'
import CreateOrder from './CreateOrder.vue'

import { storeToRefs } from 'pinia';
import { useUserInfo } from '/@/stores/userInfo'
export default {
  name: 'DraftList',
  props: {
    dialogDrawer: {
      type: Boolean,
      default: false
    }
  },
  components: {
    CreateOrder
  },
  setup(props, context) {
    const { dialogDrawer } = toRefs(props)
    // 用户信息
    const storeUserInfo = useUserInfo() // 订单各类状态数据
    const { userInfos } = storeToRefs(storeUserInfo)
    const drawer = computed({
      get: () => dialogDrawer.value,
      set: val => {
        context.emit('update:dialogDrawer', val)
      }
    })
    const orderApi = useOrderApi()
    const state = reactive({
      list: [],
      dialogEdit: false,
      rowForm: {},
      editStatus: false,
      userId: userInfos.value.id,
      draftId: ''
    })
    watch(() => dialogDrawer.value,
      val => {
        if(val) {
          getDraft()
        }
      }
    )
    const close = () => {
      context.emit('update:dialogDrawer', false)
    }
    // 编辑
    const editDraft = (row) => {
      state.rowForm = row
      state.dialogEdit = true
    }
    // 删除
    const delDraft = (row) => {
      ElMessageBox.confirm(
          `是否确定删除草稿${row.memberUsername}`,
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
      ).then(() => {
          orderApi.delDraft(state.draftId).then(() => {
            ElMessage.success('删除成功')
            getDraft()
          })
      })
    }
    // 获取草稿
    const getDraft = () => {
      orderApi.getDraftDetail({
          userId: state.userId,
          type: 0
      }).then(res => {
          state.draftId = res.data.id
          if(res.data.contents) {
              state.list[0] = JSON.parse(res.data.contents)
          }
      })
    }
    return { 
      ...toRefs(state),
      drawer,
      close,
      editDraft,
      delDraft
    }
  }
}
</script>

<style>

</style>